$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/agent/businesslist',
        datatype: "json",
        colModel: [
            { label: '业务员名称', name: 'username', index: 'username', width: 130 },
            { label: '业务员手机', name: 'mobile', index: 'mobile', width: 120 },
            { label: '所属代理商', name: 'agent', index: 'agent', width: 120 },
            { label: '佣金百分比', name: 'commission', index: 'commission', width: 110 },
            { label: '密码线条数', name: 'id', index: 'id', width: 80,formatter: function(cellvalue, options, rowdata) {
                    var num = 0;
                    $.ajax({
                        type: "POST",
                        async:false,
                        url: baseURL + "sys/agent/querySaleLineCodeNum/"+rowdata.userId,
                        success: function(r){
                            num = r.num;
                        }
                    });
                    return num;
                } },
            { label: '状态', name: 'status', width: 80, formatter: function(value, options, row){
                    return value === 1 ?
                        '<span class="label label-success">正常</span>' :
                        '<span class="label label-danger">异常</span>';
                }},

            { label: '操作', name: 'sy', width: 100,align:'center',formatter: function(cellvalue, options, rowdata) {
                    return "<a style='cursor:pointer;' class='btn btn-primary' onclick='vm.busManager("+ rowdata.userId +")'>"+
                        "商户</a>&nbsp;&nbsp;&nbsp;&nbsp;"+
                        "<a style='cursor:pointer;' class='btn btn-primary' onclick='vm.statistics("+ rowdata.userId +")'>" +
                        "统计";
                }}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        q: {
            busParent: null,
            busName: null,
            busPhone: null,
            status: null
        },
        qcx: {
            shopName: null,
            shopPhone: null,
            status: null
        },
        dlstj:{
            orderSn: null,
            userid: null
        },
        qsh:{
            name: null,
            address: null,
            userid: null
        },
		showList: true,
		title: null,
		agentShopBus: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
        queryBus: function () {
            vm.reloadBus();
        },
        queryywy:function () {
            vm.reloadAgentTj();
        },
        querysh:function () {
            vm.reloadMerchant();
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.agentShopBus = {};
		},
        update: function (id) {
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        busManager : function(agentid) {
            vm.qsh.userid = agentid;

            $.jgrid.gridUnload("jqGridAddSH");
            $("#jqGridAddSH").jqGrid({
                url: baseURL + 'sys/merchant/merchantpage',
                datatype: "json",
                colModel: [
                    { label: '商户名称', name: 'name', index: 'name', width: 120 },
                    { label: '店铺负责人', name: 'username', index: 'username', width: 120},
                    { label: '密码线条数', name: 'userid', index: 'userid', width: 100,formatter: function(cellvalue, options, rowdata) {
                            var num = 0;
                            $.ajax({
                                type: "POST",
                                async:false,
                                url: baseURL + "sys/merchant/queryLineCodeNum/"+rowdata.userid,
                                success: function(r){
                                    num = r.num;
                                }
                            });
                            return num;
                        } },
                    { label: '分佣比例', name: 'businessRatio', index: 'businessRatio', width: 100 },
                    { label: '详细地址', name: 'address', index: 'ADDRESS', width: 120 },
                    { label: '店铺电话', name: 'shopPhone', index: 'SHOP_PHONE', width: 100 }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPagerSH",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                postData : {userid:agentid},
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridAddSH").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            $('#myModalSH').modal();
        },
        statistics :function (userid) {
            vm.dlstj.userid = userid;

            $.jgrid.gridUnload("jqGridAdddls");
            $("#jqGridAdddls").jqGrid({
                url: baseURL + 'sys/shoporder/salelist',
                datatype: "json",
                colModel: [
                    { label: '用户', name: 'userId', index: 'USER_ID', width: 150,formatter: function(cellvalue, options, rowdata) {
                            var username="" ;
                            $.ajax({
                                type: "POST",
                                async:false,
                                url: baseURL + "sys/users/info/"+rowdata.userId,
                                success: function(r){
                                    username = r.users.username;

                                }
                            });
                            return username;
                        }
                    },
                    { label: '订单状态', name: 'orderStatus', width: 130, formatter: function(value, options, row){
                            if (value ==0) {
                                return '<span class="label label-danger">租借中</span>' ;
                            }  else if (value ==1) {
                                return '<span class="label label-danger">已完成</span>' ;
                            }  else if (value ==2) {
                                return '<span class="label label-danger">已撤销</span>' ;
                            }
                        }},
                    { label: '二维码编号', name: 'qcode', index: 'qcode', width: 150},
                    { label: '使用时长', name: 'useduration', index: 'useDuration', width: 110 },
                    { label: '实付金额', name: 'actualAmount', index: 'actual_amount', width: 110 }

                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPagerdls",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                postData : {userid:userid},
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridAdddls").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            $('#myModaldls').modal();
        },
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                // vm.agentShopBus.busParent = $("#agentParent").text();
                var url = vm.agentShopBus.id == null ? "sys/agentshopbus/save" : "sys/agentshopbus/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.agentShopBus),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (id) {
			// var ids = getSelectedRows();
			// if(ids == null){
			// 	return ;
			// }
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "sys/agentshopbus/deleteById",
                        contentType: "application/json",
                        data: JSON.stringify(id),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},

        addAgent: function () {
            $("#jqGridAdd").jqGrid({
                url: baseURL + 'sys/agent/list',
                datatype: "json",
                colModel: [
                    // { label: 'id', name: 'id', index: 'ID', width: 50, key: true },
                    { label: '代理商名称', name: 'shopName', index: 'SHOP_NAME', width: 80 },
                    { label: '代理商手机', name: 'shopPhone', index: 'SHOP_PHONE', width: 80 },
                    // { label: '代理模式 0 购买设备 1 投放设备', name: 'shopType', index: 'SHOP_TYPE', width: 80 },
                    { label: '代理模式', name: 'shopType', width: 80, formatter: function(value, options, row){
                            return value === 0 ?
                                '<span class="label label-danger">购买设备</span>' :
                                '<span class="label label-success">投放设备</span>';
                        }},
                    { label: '代理商上级', name: 'shopParent', index: 'SHOP_PARENT', width: 80 },
                    { label: '佣金百分比', name: 'shopRatio', index: 'SHOP_RATIO', width: 80 },
                    // { label: '0 可打开所属机柜 1 不可打开', name: 'isopen', index: 'isOPEN', width: 80 },
                    { label: '可打开所属机柜', name: 'isopen', width: 80, formatter: function(value, options, row){
                            return value === 0 ?
                                '<span class="label label-danger">是</span>' :
                                '<span class="label label-success">否</span>';
                        }},
                    // { label: '所属系统', name: 'sysSystem', index: 'SYS_SYSTEM', width: 80 },
                    // { label: '状态 0 正常 1 禁用', name: 'status', index: 'STATUS', width: 80 },
                    { label: '状态', name: 'status', width: 80, formatter: function(value, options, row){
                            return value === 0 ?
                                '<span class="label label-danger">正常</span>' :
                                '<span class="label label-success">禁止</span>';
                        }},
                    // { label: '备注', name: 'remarks', index: 'REMARKS', width: 80 },
                    // { label: '创建时间', name: 'createdTime', index: 'CREATED_TIME', width: 80 },
                    // { label: '登录密码', name: 'loginPassword', index: 'LOGIN_PASSWORD', width: 80 }
                    { label: '操作', name: 'sy', width: 70,align:'center',formatter: function(cellvalue, options, rowdata) {
                            return "<a style='cursor:pointer;' onclick='vm.shopChoose("+ rowdata.id +")'>" +
                                "<span class='btn btn-primary'>选择</span></a>&nbsp;&nbsp;&nbsp;&nbsp;" ;
                        }}
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPager1",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridAdd").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            // vm.queryGroup();
            $('#myModal').modal();
        },
        shopChoose:function (id) {
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/agent/info/"+id,
                success: function(r){
                    $("#agentParent").html("");
                    $("#agentParent").append(r.agent.shopName);
                    vm.agentShopBus.busParent=r.agent.id;
                }
            });
            $('#myModal').modal("hide");

        },
		getInfo: function(id){
			$.get(baseURL + "sys/agentshopbus/info/"+id, function(r){
                //代理商
                $.ajax({
                    type: "POST",
                    async:false,
                    url: baseURL + "sys/agent/info/"+r.agentShopBus.busParent,
                    success: function(r1){
                        $("#agentParent").text(r1.agent.shopName);
                    }
                });
                vm.agentShopBus = r.agentShopBus;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData: {'status': vm.q.status,
                    'busParent': vm.q.busParent,
                    'busName': vm.q.busName,
                    'busPhone': vm.q.busPhone
                },
                page:page
            }).trigger("reloadGrid");
		},
        reloadBus: function (event) {
            var page = $("#jqGridAdd").jqGrid('getGridParam','page');
            $("#jqGridAdd").jqGrid('setGridParam',{
                postData: {'status': vm.qcx.status,
                    'shopName': vm.qcx.shopName,
                    'shopPhone': vm.qcx.shopPhone
                },
                page:page
            }).trigger("reloadGrid");
        },
        reloadAgentTj: function (event) {
            var page = $("#jqGridAdddls").jqGrid('getGridParam','page');
            $("#jqGridAdddls").jqGrid('clearGridData');  //清空表格
            $("#jqGridAdddls").jqGrid('setGridParam',{
                postData: {'userid': vm.dlstj.userid,
                    'orderSn': vm.dlstj.orderSn
                },
                page:page
            }).trigger("reloadGrid");
        },
        reloadMerchant: function (event) {
            var page = $("#jqGridAddSH").jqGrid('getGridParam','page');

            $("#jqGridAddSH").jqGrid('clearGridData');  //清空表格
            $("#jqGridAddSH").jqGrid('setGridParam',{
                postData: {'userid': vm.qsh.userid,
                    'name': vm.qsh.name,
                    'address': vm.qsh.address
                },
                page:page
            }).trigger("reloadGrid");
        }
	}
});